package mail.util;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.InvalidParameterException;
import java.util.Date;
import java.util.Objects;

/**
 * @author: Hanjiafeng
 * @date: Created in 11:39 2019/3/11
 * @desc: fetch公共方法集
 */
public class PublicMethod {

    private static final long HALF_YEAR_MILLI_SECOND = (180L * 24 * 60 * 60 * 1000);

    /**
     * 判断输入时间是否在半年之内
     *
     * @param checkedDate 待检测日期
     * @return 是否在半年之内
     */
    public static boolean isDuringHalfYear(Date checkedDate) {

        long checkedTimeMills = checkedDate.getTime();
        //当前时间
        long currentMills = System.currentTimeMillis();
        //计算时间差
        long deviationMillis = currentMills - checkedTimeMills;

        return deviationMillis < HALF_YEAR_MILLI_SECOND;
    }


    /**
     * 从url获取指定文本
     *
     * @param client             发送者
     * @param baseRequestBuilder 基础请求
     * @param uri                链接
     * @return 链接内容
     * @throws IOException          io
     * @throws InterruptedException in
     */
    public static String getTextFromUrl(HttpClient client, HttpRequest.Builder baseRequestBuilder, String uri) throws IOException,
            InterruptedException {

        HttpRequest request = baseRequestBuilder
                .copy()
                .setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .uri(URI.create(uri))
                .build();
        HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        return HttpResponseUtil.getBody(response);
    }

    /**
     * 使用GET方法根据指定type获取响应头参数
     *
     * @param httpClient     httpClient
     * @param requestBuilder 请求体
     * @param type           返回参数类型
     * @param uri            目的地址
     * @param headers        请求头
     * @return 响应头参数
     * @throws IOException          io
     * @throws InterruptedException in
     */
    public static String getResponseElement(HttpClient httpClient, HttpRequest.Builder requestBuilder,
                                            String uri, ResponseElement type, String... headers) throws IOException, InterruptedException {
        return getResponseElementT(httpClient, requestBuilder, uri, null, type, headers);
    }

    /**
     * 使用POST方法根据指定type获取响应头参数
     *
     * @param httpClient     httpClient
     * @param requestBuilder 请求体
     * @param type           返回参数类型
     * @param uri            目的地址
     * @param postData       post data
     * @param headers        请求头
     * @return 响应头参数
     * @throws IOException          io
     * @throws InterruptedException in
     */
    public static String getResponseElement(HttpClient httpClient, HttpRequest.Builder requestBuilder,
                                            String uri, String postData, ResponseElement type, String... headers) throws IOException, InterruptedException {
        if (Objects.isNull(postData)) {
            throw new InvalidParameterException("POST data is null");
        }
        return getResponseElementT(httpClient, requestBuilder, uri, postData, type, headers);
    }

    /**
     * 基础请求方法
     *
     * @param httpClient     httpClient
     * @param requestBuilder 请求体
     * @param type           返回参数类型
     * @param uri            目的地址
     * @param postData       post data
     * @param headers        请求头
     * @return 响应头参数
     * @throws IOException          io
     * @throws InterruptedException in
     */
    private static String getResponseElementT(HttpClient httpClient, HttpRequest.Builder requestBuilder, String uri,
                                              String postData, ResponseElement type, String... headers) throws IOException, InterruptedException {

        //先复制一份
        requestBuilder = requestBuilder
                .copy();
        //如果postData不为null,设置为post请求
        if (!Objects.isNull(postData)) {
            requestBuilder.method("POST", HttpRequest.BodyPublishers.ofString(postData));
        }
        HttpRequest httpRequest = requestBuilder
                .headers(headers)
                .uri(URI.create(uri))
                .build();
        HttpResponse<byte[]> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofByteArray());
        switch (type) {
            case LOCATION:
                return HttpResponseUtil.getLocation(response);
            case BODY:
                return HttpResponseUtil.getBody(response);
            case NOTHING:
                //返回null
            default:
                return null;
        }
    }
}
